//
//  FPLoanDetailController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/2/8.
//

#import "FPLoanDetailController.h"
#import "FPLoanDetailHeader.h"
#import "FPLoanDetailCell.h"
#import "FPLoanDetailBarrierView.h"
#import "FPRepayController.h"
#import "FPLoanDetailModel.h"

@interface FPLoanDetailController () <UITableViewDelegate , UITableViewDataSource , DZNEmptyDataSetSource , DZNEmptyDataSetDelegate , UIScrollViewDelegate>

@property (nonatomic , strong) FPLoanDetailHeader *headerView;
@property (nonatomic , strong) FPLoanDetailBarrierView *barrierView;

@property (nonatomic , strong) NSMutableArray *leftSource;
@property (nonatomic , strong) NSMutableArray *rightSource;
@property (nonatomic , assign) FPLoanDetailType type;
@property (nonatomic , strong) NSString *totalLengthOfMaturity; //!< 总期数

@end

@implementation FPLoanDetailController

LazyLoadDataSource(leftSource);
LazyLoadDataSource(rightSource);

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)initUI {
    
    self.type = FPLoanDetailTypeBorrowing;
    
    [self setTitle:@"借款详情" style:(XYCustomNavigationStyleClear) hiddenBackBtn:NO];
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight);
    
    self.tableView.backgroundColor = UIColor.clearColor;
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPLoanDetailHeader.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    
    // iOS 15+ 解决顶部间距问题
    if (@available(iOS 15.0, *)) {
        self.tableView.sectionHeaderTopPadding = 0; // 取消自动顶部间距
    }
    
    self.tableView.rowHeight = 126.f;
    
    // 设置默认显示 待还款/已还款
    [self.barrierView showStatusWithIndex:self.type];
    
    [self.barrierView.lab1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIndex:)]];
    [self.barrierView.lab2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeIndex:)]];
    
    [self getData];
}

- (void)getData {
    
    NSString *param = @"0";
    
    if (self.type == FPLoanDetailTypeRepayment) {
        
        param = @"1";
    }
    
#warning 在 V2 已删
//    [MBManager showLoading];
//    [FPLoanDetailModel getDataWithID:self.loanID status:param success:^(NSInteger code, NSString * _Nonnull message, FPLoanDetailModel *model) {
//        [MBManager hideLoading];
//        
//        if (self.type == FPLoanDetailTypeBorrowing) {
//            
//            [self.leftSource removeAllObjects];
//            
//            for (FPLoanDetailListModel *m in model.repaymentScheduleVo) {
//                
//                [self.leftSource addObject:m];
//            }
//            
//            self.headerView.amountLab.text = model.totalAmount;
//            self.totalLengthOfMaturity = model.totalLengthOfMaturity;
//            
//            double amount = 0.f;
//            double rate = 0.f;
//            for (FPLoanDetailListModel *m in self.leftSource) {
//                    
//                amount += m.principal.doubleValue;
//                rate += m.interest.doubleValue;
//            }
//            
//            self.headerView.retaLab.text = [NSString stringWithFormat:@"剩余待还 本金：%.2f元 ｜ 利息：%.2f元" , amount , rate];
//        }
//        else {
//            
//            [self.rightSource removeAllObjects];
//            
//            for (FPLoanDetailListModel *m in model.repaymentScheduleVo) {
//                
//                [self.rightSource addObject:m];
//            }
//            
//        }
//        
//        [self.tableView reloadData];
//        
//    } failure:^(NSError * _Nonnull error) {
//        [self showError:error];
//    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 35.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return self.barrierView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.type == FPLoanDetailTypeBorrowing) {
        
        return self.leftSource.count;
    }
    else if (self.type == FPLoanDetailTypeRepayment) {
    
        return self.rightSource.count;
    }

    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPLoanDetailCell *cell;
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPLoanDetailCell.class) owner:nil options:nil].lastObject;
    }
    
    cell.repayBtn.indexPath = indexPath;
    
    FPLoanDetailListModel *model;
    
    // repayBtn 在v2版本已经是永久隐藏状态 还款入口在"我的" -> 金刚区上面
    // 待还款
    if (self.type == FPLoanDetailTypeBorrowing) {
        
        if (indexPath.row > 0) {
            
            cell.repayBtn.hidden = YES;
        }
        
        model = self.leftSource[indexPath.row];
        
        [cell.repayBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
           
            [self toRepayAction:cell.repayBtn];
        }];
    }
    // 已还款
    else {
        
        cell.repayBtn.hidden = YES;
        
        model = self.rightSource[indexPath.row];
    }
    
    NSString *term;
      
    if (self.totalLengthOfMaturity) {
     
        term = [FPLoanDetailModel termOfParam:self.totalLengthOfMaturity];
    }
    
    cell.periodLab.text = [NSString stringWithFormat:@"%02zd/%@期",model.installmentNumber.integerValue, term];
    cell.amountLab.text = [NSString stringWithFormat:@"%.2f",model.amount.floatValue];
    cell.retaLab.text = [NSString stringWithFormat:@"本金：%.2f + 利息：%.2f",model.principal.floatValue , model.interest.floatValue];
    cell.timeLab.text = [NSString stringWithFormat:@"还款日：%@",[FPLoanDetailModel timeOfParam:model.repaymentDate]];
    
    return cell;
}

- (FPLoanDetailBarrierView *)barrierView {
    
    if (!_barrierView) {
        
        _barrierView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPLoanDetailBarrierView.class) owner:nil options:nil].lastObject;
    }
    
    return _barrierView;
}

- (void)changeIndex:(UITapGestureRecognizer *)sender {
    
    if ([sender.view isEqual:self.barrierView.lab1]) {
        
        if (self.type == FPLoanDetailTypeBorrowing) {
            
            return;
        }
        
        self.type = FPLoanDetailTypeBorrowing;
    }
    else {
        
        if (self.type == FPLoanDetailTypeRepayment) {
            
            return;
        }
        
        self.type = FPLoanDetailTypeRepayment;
    }
    
    [UIView animateWithDuration:.15f animations:^{
        
        [self.tableView setContentOffset:CGPointMake(0.f, 0.f)];
        
    }completion:^(BOOL finished) {
        
        [self.barrierView changeStatusWithIndex:self.type];
        
        [self getData];
    }];
}

#pragma mark - 去还款
- (void)toRepayAction:(FPCustomBtn *)sender {
    
    NSIndexPath *ip = sender.indexPath;
    
//    [self showText:@"去还款~"];
    
    NSString *term;
    if (self.totalLengthOfMaturity) {
     
        term = [FPLoanDetailModel termOfParam:self.totalLengthOfMaturity];
    }
    
    FPLoanDetailListModel *model = self.leftSource[ip.row];
    
    FPRepayController *vc = [[FPRepayController alloc] init];
    vc.amountString = model.amount;
    vc.termString = [NSString stringWithFormat:@"%02zd/%@期",model.installmentNumber.integerValue, term];
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    return IMG(@"bg_nodata_repayment");
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {

    return 0.f;
}



- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    NSString *text;
    
    if (self.type == FPLoanDetailTypeBorrowing) {
        
        text = @"暂无待还款";
    }
    else if (self.type == FPLoanDetailTypeRepayment) {
        
        text = @"暂无已还款";
    }
    
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [NSString stringToAttribute:attStr font:FONT(12.f) range:NSMakeRange(0, text.length)];
    [NSString stringToAttribute:attStr color:[UIColor hexColor:@"#6A6A6A"] range:NSMakeRange(0, text.length)];

    return attStr;
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView {
    
    return -50.f;
}


@end
